import moment from 'moment';
import user from '@/content/api/user'
import usermeta from '@/content/api/usermeta'
import {SqlLibUser} from "../../../../../static/lib/sqlite/service/SqlLibUser";
import {SqlLib} from "../../../../../static/lib/sqlite/SqlLib";
import {RecUserResource} from "../../../../../static/lib/sqlite/model/RecUserResource";
import {RecUserTime} from "../../../../../static/lib/sqlite/model/RecUserTime";
import { SqlLibBook } from '../../../../../static/lib/sqlite/service/SqlLibBook';
import {collectUserPoint} from  '../../api/point'
// import { log } from 'builder-util';
let hangupTime = 0;
window.countTimeInterval = null;

const weedMetaId = ['countDown', 'extractNumber', 'tProgress', 'charts', 'mindMap','Picture','recognize']
const weedMetaIdMap = {
    countDown:'CountDown',
    extractNumber:'ExtractNumber',
    tProgress:'TProgress',
    charts:'Charts',
    mindMap:'MindMap',
    Picture:'ImageTrans',
    recognize: 'ReadPic',
}

function hangupEvent(){
    document.addEventListener("click",initHangUpTime);
    document.addEventListener("keydown",initHangUpTime);
    document.addEventListener("mousemove",initHangUpTime);
    document.addEventListener("mousewheel",initHangUpTime);
}

function initHangUpTime() {
    hangupTime = 0;
    if(!window.countTimeInterval){//如果触发了点击/鼠标/键盘事件，就继续计时
        updateTime();
    }
}

let timeSub = 0

function updateTime() {
    console.log("I'm updateTime... ")
    console.log(localStorage.isOffline);
    if(localStorage.isOffline !== "true"){//在线
        setTimeout(function () {
            let tempTime = new RecUserTime();
            let sqlLib = SqlLib.getInstance(window.$DBDIR);
            let currentUser = SqlLibUser.queryCurrentUser(sqlLib);
            tempTime.userId = currentUser.id;
            let userRecTimes = sqlLib.selectAllObjectByKeys(tempTime, ["userId"]);
            console.log('userRecTimes离线使用时长' , userRecTimes);
            if (!userRecTimes) {
                return
            }
            userRecTimes.forEach(times => {
                user.updateOfflineTime({
                    offlineTime: times.minuteCount,
                    dayStr: times.timeDay
                }).then((res) => {
                    if (res.code == '0') {
                        sqlLib.deleteObjectByKey(tempTime, "userId");
                    }
                    console.log('增加离线使用时长记录----------',times.minuteCount);
                }).catch(error => {})
            });
        }, 1000);
        setTimeout(()=>{
            collectClassTime()
        },2000)
    }
    if(window.countTimeInterval){
        clearInterval(window.countTimeInterval);
    }
    window.countTimeInterval = setInterval(function () {
        hangupTime = hangupTime + 1;//统计未点击页面时间的时间
        if(hangupTime > 40){//超过四十分钟无点击等事件，清除计时器
            if(window.countTimeInterval){
                clearInterval(window.countTimeInterval);
                window.countTimeInterval = null;
                hangupTime = 0;
            }
        }else {
            
            console.log("I'm running... 增加1分钟时长")
            
            if(localStorage.isOffline !== "true"){//在线状态
                timeSub += 1 
                if(timeSub >= 10){
                    collectUserPoint({channel:10}).then(res => {
                        if(res.code === '0'){
                            console.log('增加20积分')
                        }
                    })
                    timeSub = 0
                }
                user.updateUseTime({}).then(response => {}).catch(error => {});
                //延迟执行
                setTimeout(function () {//todo  本地库存储的时间发往服务端
                    let tempUser = new RecUserResource();
                    let sqlLib = SqlLib.getInstance(window.$DBDIR);
                    let currentUser = SqlLibUser.queryCurrentUser(sqlLib);
                    if(currentUser){
                        tempUser.userId = currentUser.id;
                        let userRecResources = sqlLib.selectAllObjectByKeys(tempUser, ["userId"]);
                        if(userRecResources && userRecResources.length !== 0){
                            let rParams = []
                            let tParams = []
                            userRecResources.forEach(userResource => {
                                if(weedMetaId.includes(userResource.metaInfoId)){
                                    tParams.push({
                                        toolType: weedMetaIdMap[userResource.metaInfoId],
                                        lessonId: userResource.lessonId,
                                        useTime: userResource.playTime,
                                        startTime: userResource.gmtCreate
                                    })
                                }else{
                                    rParams.push({
                                        metaInfoId: userResource.metaInfoId,
                                        metaType: userResource.metaType,
                                        lessonId: userResource.lessonId,
                                        createTime: userResource.gmtCreate,
                                        playTime: userResource.playTime
                                    });
                                }
                            });
                            let promiseArray = []
                            console.log('rParams---->',rParams);
                            if(rParams.length > 0){
                                console.log('调用离线统计播放资源时长');
                                promiseArray.push(usermeta.syncUserResRecord({
                                    syncUserRecordDTOS: rParams
                                }))
                            }
                            if(tParams.length > 0){
                                promiseArray.push(usermeta.recordUseTechTool({
                                    useTechToolDTOList: tParams
                                }))
                            }
                            //同步资源点击记录
                            Promise.all(promiseArray).then((response) => {
                                sqlLib.deleteObjectByKey(tempUser, "userId")
                            }).catch(() => { sqlLib.deleteObjectByKey(tempUser, "userId") });
                        }
                    }
                }, 1000);
            }else if(localStorage.isOffline == "true") {//离线状态
                let nowDay = moment().format("YYYY-MM-DD");
                let nowTime = moment().format("YYYY-MM-DD HH:mm:ss");
                let sqlLib = SqlLib.getInstance(window.$DBDIR);
                let currentUser = SqlLibUser.queryCurrentUser(sqlLib);
                if(currentUser){
                    SqlLibUser.updateUserTime(sqlLib, currentUser.id, nowDay, nowTime);
                }
            }
            
        }
    }, 60 * 1000);
}

updateTime();
hangupEvent();

export function collectClassTime(){
    let sqlLib = SqlLib.getInstance(window.$DBDIR)
    let classTimeArry = SqlLibBook.querAllClassTime(sqlLib)
    console.log('classTimeArry',classTimeArry)
    if(classTimeArry&&Array.isArray(classTimeArry)&&classTimeArry.length > 0){
        let data = []
        let map = {
            userId:'userId',
            startId:'id',
            totalTime:'btwTime',
            createTime:'reverse1'
        }
        classTimeArry.forEach(classTimeItem => {
            let obj = {};
            let arry = ['userId','startId','totalTime','createTime']
            arry.forEach(key => {
                obj[key] = classTimeItem[map[key]]
            })
            data.push(obj)
        })
        console.log(data)
        user.recordUserClass({userRecordClassDTOS:data}).then(res => {
            if(res.code==='0'){
                SqlLibBook.clearEventsTable(sqlLib)
                SqlLibBook.clearClassTimeTable(sqlLib)
            }else{
                console.log(res)
            }
        })
        //调取接口 
    }
}


// let initMessages = null
// function getPostMessage(){
//     if(localStorage.isOffline !== "false"){
//         window.postMessageInterval || clearInterval(window.postMessageInterval)
//         return
//     }
//     window.postMessageInterval = setInterval(() => {
//         user.getAllPostMessage().then(res=>{
//             if(res.code==='0'){
//                 if(initMessages === null){
//                     initMessages = res.returnValue.length
//                     let noAllread = res.returnValue.filter(message => {
//                         return message.isRead === '0'
//                     })
//                     if(noAllread.length>0){
//                         let haveNewMessage = new BroadcastChannel('push-messgae-has-been-updated')
//                         haveNewMessage.postMessage({tip:'您有新的消息待查看',num:noAllread.length  })
//                     }
//                     console.log('initMessages=>>>>',initMessages)
//                 }else{
//                     let refreshMessages = res.returnValue.length
//                     console.log('refreshMessages=>>>>',initMessages)
//                     if(refreshMessages > initMessages ){
//                         let haveNewMessage = new BroadcastChannel('push-messgae-has-been-updated')
//                         haveNewMessage.postMessage({tip:'您有新的消息待查看',updateNum:refreshMessages - initMessages})
//                     }
//                 }
//             }
//         })
//     }, 10*60*1000);


// }

// getPostMessage()
